package yb.ecp.fast.user.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.user.dao.entity.AccountDO;
import yb.ecp.fast.user.dao.entity.ProfileDO;
import yb.ecp.fast.user.dao.mapper.AccountMapper;
import yb.ecp.fast.user.dao.mapper.ProfileMapper;
import yb.ecp.fast.user.exception.AuthException;
import yb.ecp.fast.user.infra.AuthConstant;
import yb.ecp.fast.user.infra.ErrorCode;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class HanyunLoginUserService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private ProfileMapper profileMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AsyncService asyncService;
    @Value("${login.recordIp.default.flag:N}")
    private String loginRecordIp;

    public Map<String, String> loginCheck(JSONObject body, String accessToken) throws UnsupportedEncodingException {
        log.info("body:{}", body);
        String realName = body.getString("realName");
        String loginName = body.getString("loginName");
        // 登陆后根据token获取用户信息-----推荐对接系统若无此用户做用户注册
        if (ObjectUtils.isEmpty(loginName)) {
            loginName = ((Map<String, Object>) body.get("data")).get("userName").toString();
            realName = loginName;
        }
        if (ObjectUtils.isEmpty(loginName)) {
            throw new AuthException("Oauth登陆失败");
        }

        AccountDO accountDO = accountMapper.selectByPrimaryKey(loginName);
        if (accountDO == null) {
            LogHelper.error("登录账号不存在！", ErrorCode.CheckLoginFailure.getCode());
            throw new AuthException(ErrorCode.CheckLoginFailure);
        }
        ProfileDO profileDO = profileMapper.selectById(accountDO.getUserId());
        if (profileDO == null || profileDO.getLocked() == AuthConstant.USER_LOCKED) {
            LogHelper.error("用户状态被锁！", ErrorCode.UserLocked.getCode());
            throw new AuthException(ErrorCode.UserLocked);
        }
        if ("Y".equals(loginRecordIp)) {
            asyncService.recordUserLoginRecord(request, accountDO.getUserId(), accountDO.getLoginName(), profileDO.getName(), profileDO.getSpaceId());
        }
        //以下为模拟操作
        Map<String, String> data = new HashMap<>();
        data.put("token", accessToken);
        data.put("realName", URLEncoder.encode(realName, "UTF-8"));
        data.put("loginName", loginName);
        data.put("userId", accountDO.getUserId());
        return data;
    }
}
